var $body = $('body'),
    sendTime = function($button, time) {
        var action = $button.data('name'),
            id = $button.data('id');

        ajaxPost('index.php', {ajax: true, action: action, id: id, time: time}, function (res) {
            if (res.error === false) {
                $button.text(res.now);
                $button.parent().next().find('.button.time.enabled');
                $button.parent().find('.button.edit.disabled').removeClass('disabled').addClass('enabled');

                $('#total_nobreak_' + id).text(res.total_nobreak);
                $('#total_' + id).text(res.total);
                $('#break_' + id).text(res.break);
                if (res.home) {
                    $('#home_' + id).text(res.home);
                }
            }
        });
    };

$body.on('click', '.button.time', function () {
    var $button = $(this),
        $date = new Date();
    if ($button.hasClass('disabled')) {
        return;
    }
    $button.addClass('disabled').removeClass('enabled');
    sendTime($button, $date.toTimeString().substr(0, 8));
});


$body.on('dblclick', '.button.time.disabled', function() {
    var $button = $(this),
        value = $button.text(),
        $input = $('<input/>').attr('type','text').attr('maxlength',8).val(value).addClass('textField');
    $button.html($input);
    $input.focus();
});

$body.on('blur', '.button .textField', function() {
    var $this = $(this),
        $button = $this.parent();
    sendTime($button, $this.val());
});

$body.on('keypress', '.textField', function(event) {
    if (event.keyCode === 13) {
        $(this).blur();
    }
});